import { login, logout } from '@/api/login'
import { getUserInfo } from '@/api/user/user'
import Cookies from 'js-cookie'

const TokenKey = 'Admin-Token'

const user = {
  state: {
    token: Cookies.get(TokenKey),
    userInfo: JSON.parse(sessionStorage.getItem("userInfo")) || {},
    roles: [],
    permissions: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo
      sessionStorage.setItem("userInfo", JSON.stringify(userInfo));
    },
    SET_USER_COVER: (state, userCover) => {
      state.userInfo.userCover = userCover;
      sessionStorage.setItem("userInfo", state.userInfo);
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(res => {
          // console.log(res);
          Cookies.set(TokenKey, res.data.data)
          commit('SET_TOKEN', res.data.data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(res => {
          let returnValue = res.data.data;
          commit('SET_USERINFO', returnValue);
          // 若头像为空，显示小电视
          const avatar = (returnValue.userCover == "" || returnValue.userCover == null) ?
            require("@/assets/img/avatar1.jpg") : process.env.VUE_APP_DOWNLOAD_URL + returnValue.userCover;
          // 验证返回的roles是否是一个非空数组
          if (returnValue.roles && returnValue.roles.length > 0) {
            commit('SET_ROLES', returnValue.roles)
            commit('SET_PERMISSIONS', returnValue.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          resolve(returnValue)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          Cookies.remove(TokenKey)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        Cookies.remove(TokenKey)
        resolve()
      })
    }
  }
}

export default user
